<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket 客户端 用这个做连接测试</title>
</head>
<body>
    <h1>WebSocket 测试</h1>
    <input id="username" type="text" placeholder="输入用户名">
    <input id="message" type="text" placeholder="输入消息">
    <input id="token" type="text" placeholder="输入 Token">
    <button onclick="connectAndSend()">连接并发送</button>
    <ul id="messages"></ul>

    <script>
        let ws;

        // 连接到 WebSocket 服务器
        function connectAndSend() {
            const token = document.getElementById("token").value;
            if (!token) {
                alert("请输入有效的 Token");
                return;
            }

            // 创建 WebSocket 连接，并在请求头中携带 Token
            ws = new WebSocket(`ws://localhost:3000/ws?token=text`, null, {
                headers: {
                    token: "text"
                }
            });

            // 监听 WebSocket 连接打开事件
            ws.onopen = () => {
		alert("连接已建立");
                sendMessage();
            };

            // 监听 WebSocket 消息事件
            ws.onmessage = (event) => {
                const data = JSON.parse(event.data);
                const messagesList = document.getElementById("messages");
                const messageItem = document.createElement("li");
                messageItem.textContent = `${data.value}`;
                messagesList.appendChild(messageItem);
            };

            // 监听 WebSocket 错误事件
            ws.onerror = (error) => {
                console.error("WebSocket 错误: ", error);
            };

            // 监听 WebSocket 关闭事件
            ws.onclose = () => {
                console.log("连接已关闭");
            };
        }

        // 发送消息到服务器
        function sendMessage() {
            const username = document.getElementById("username").value;
            const message = document.getElementById("message").value;
	    //tlv:
            ws.send(JSON.stringify({ type: 1001, length: message.length, value: message }));

            document.getElementById("message").value = "";
        }
    </script>
</body>
</html>